
package com.hxrk.cecardvr;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.os.RemoteException;
import android.os.StatFs;

import com.hxrk.aidlservice.ServiceBinder;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;

public class Utils {
    private static final String TAG = "Utils";

    public static String putTextCPHM = "";
    public static int putTextSpeed = 0;
    public static double longitude = 0;
    public static double latitude = 0;
    public static String deviceVersion = "";
    public static String cardName = "";
    // 0关  1 开
    public static int accZT = -1;
    public static String putText = "";
    public static String simNo = "18888888888";    //1078协议需要的终端的SIM卡号

    //[1]USB [2]MIPI  其它待定义
    public static int[] fileNumber = {0, 0, 0, 0, 0, 0, 0};

    /**
     * 将字符串转为16进制BCD码
     * @param asc
     * @return
     */
    public static byte[] StrToBCDBytes(String asc) {
        int len = asc.length();
        int mod = len % 2;
        if (mod != 0) {
            asc = "0" + asc;
            len = asc.length();
        }
        byte abt[] = new byte[len];
        if (len >= 2) {
            len = len / 2;
        }
        byte bbt[] = new byte[len];
        abt = asc.getBytes();
        int j, k;
        for (int p = 0; p < asc.length() / 2; p++) {
            if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) {
                j = abt[2 * p] - '0';
            } else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) {
                j = abt[2 * p] - 'a' + 0x0a;
            } else {
                j = abt[2 * p] - 'A' + 0x0a;
            }
            if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) {
                k = abt[2 * p + 1] - '0';
            } else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) {
                k = abt[2 * p + 1] - 'a' + 0x0a;
            } else {
                k = abt[2 * p + 1] - 'A' + 0x0a;
            }
            int a = (j << 4) + k;
            byte b = (byte) a;
            bbt[p] = b;
        }
        return bbt;
    }

    /**
     * 获取内置SD卡媒体储存路径
     *
     * @return
     */
    public static String getPath1() {
        String sd_default = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        if (sd_default.endsWith("/")) {
            sd_default += "MediaData";
        } else {
            sd_default += "/MediaData";
        }
        File file = new File(sd_default);
        if (!file.exists())
            file.mkdirs();
        return sd_default;
    }

//    /**
//     * @return
//     */
//    public static String getPath2() {
//        String sdcard_path = "";
//        String sd_default = Environment.getExternalStorageDirectory()
//                .getAbsolutePath();
//        if (sd_default.endsWith("/")) {
//            sd_default = sd_default.substring(0, sd_default.length() - 1);
//        }
//        // 得到路径
//        try {
//            Runtime runtime = Runtime.getRuntime();
//            Process proc = runtime.exec("mount");
//            InputStream is = proc.getInputStream();
//            InputStreamReader isr = new InputStreamReader(is);
//            String line;
//            BufferedReader br = new BufferedReader(isr);
//            while ((line = br.readLine()) != null) {
//                if (line.contains("secure"))
//                    continue;
//                if (line.contains("asec"))
//                    continue;
//                if (line.contains("fat") && line.contains("/mnt/")) {
//                    String columns[] = line.split(" ");
//                    if (columns != null && columns.length > 1) {
//                        if (sd_default.trim().equals(columns[1].trim())) {
//                            continue;
//                        }
//                        sdcard_path = columns[1];
//                    }
//                } else if (line.contains("fuse") && line.contains("/mnt/")) {
//                    String columns[] = line.split(" ");
//                    if (columns != null && columns.length > 1) {
//                        if (sd_default.trim().equals(columns[1].trim())) {
//                            continue;
//                        }
//                        sdcard_path = columns[1];
//                    }
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        if (sdcard_path.equals("/mnt/runtime/write/EF14-0FE4") || sdcard_path.equals("/mnt/runtime/write/065E-DC0E") || sdcard_path.equals("/mnt/runtime/write/12F7-60CF")) {
//            return "/storage/sdcard1";
//        } else
//            return "";
//    }

    /**
     * 获取外置SD卡媒体储存路径
     *
     * @return ""外置SD卡不存在
     */
    public static String getPath2() {
        String sdcard_path = getPath2_base();

        if (!sdcard_path.isEmpty()) {
            File file = new File(sdcard_path + "/MediaData");
            file.mkdirs();
            return sdcard_path + "/MediaData";
        } else
            return "";
    }

    /**
     * 获取外置SD卡报警目录
     *
     * @return ""外置SD卡不存在
     */
    public static String getPathAlarm() {
        String sdcard_path = getPath2_base();

        if (!sdcard_path.isEmpty()) {
            File file = new File(sdcard_path + "/MediaAlarm");
            file.mkdirs();
            return sdcard_path + "/MediaAlarm";
        } else
            return "";
    }

    /**
     * @return
     */
    public static String getPath2_base() {
        String sdcard_path = "/storage/sdcard1";
        File file = new File(sdcard_path);

        if (file.exists()) {
            return sdcard_path;
        } else
            return "";
    }

    public static String getPath3() {
        String sdcard_path = "";
        String sd_default = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        if (sd_default.endsWith("/")) {
            sd_default = sd_default.substring(0, sd_default.length() - 1);
        }
        // 得到路径
        try {
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec("mount");
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            String line;
            BufferedReader br = new BufferedReader(isr);
            while ((line = br.readLine()) != null) {
                if (line.contains("secure"))
                    continue;
                if (line.contains("asec"))
                    continue;
                if (line.contains("fat") && line.contains("/mnt/")) {
                    String columns[] = line.split(" ");
                    if (columns != null && columns.length > 1) {
                        if (sd_default.trim().equals(columns[1].trim())) {
                            continue;
                        }
                        sdcard_path = columns[1];
                    }
                } else if (line.contains("fuse") && line.contains("/mnt/")) {
                    String columns[] = line.split(" ");
                    if (columns != null && columns.length > 1) {
                        if (sd_default.trim().equals(columns[1].trim())) {
                            continue;
                        }
                        sdcard_path = columns[1];
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (sdcard_path.equals("/mnt/external_sd")) {
            return sdcard_path;
        } else
            return sd_default;
    }

    //devType摄像头类型1:USB  2:MIPI  isAddNumber:是否添加文件后缀序号    mediaType 0：视频   1：图片   2：录音
    public static String getCreatFileName(int devType, boolean isAddNumber, String tag, int mediaID, int mediaType, int Cause) {
        String pathname = "";
        try {
            boolean bFlag;
            String path = "";
            String pathSD = Utils.getPath2();

            if (mediaType == 0){
                if (pathSD.isEmpty()) {
                    path = Utils.getPath1();
                    //根据内置SD卡大小删除SD文件
                    bFlag = Utils.deleteFileSize(path, 0);
                } else {
                    path = pathSD;
                    //根据外置SD卡大小删除SD文件
                    bFlag = Utils.deleteFileSize(path, 1);
                }
            }else {
                if (pathSD.isEmpty()) {
                    path = Utils.getPath1();
                } else {
                    path = pathSD;
                }
                bFlag = true;
            }

            if (!path.isEmpty() && bFlag) {
                String fileTime = new SimpleDateFormat("yyyy-MM-dd_HHmmss").format(System
                        .currentTimeMillis());

                String fileParent = new SimpleDateFormat("yyyy-MM-dd").format(System
                        .currentTimeMillis()) + "/";

                String lock_flag = CamService.lock_v == 1 ? "lock" : "";
                lock_flag += CamService.flag_v == 1 ? "flag" : "";
                String mediatstr = "/Video/";
                String devTypestr = "";
                if (devType == CamParameter.DEV_TYPE_USB)
                    devTypestr = "Back/";
                if (devType == CamParameter.DEV_TYPE_MIPI)
                    devTypestr = "Front/";

                String Causestr = "中心主动拍照";
                switch (mediaType) {
                    case 0: {
                        mediatstr = "/Video/" + fileParent + devTypestr;
//                        if ((((MyApplication.BJBZ905 >> 0) & 0x01) == 1 || ((MyApplication.BJBZ905 >> 1) & 0x01) == 1)) {
//                            Causestr = "报警录像";
//                            mediatstr = "/Video/" + fileParent + Causestr + "/" + devTypestr;
//                        }
                    }
                    break;
                    case 1: {
                        mediatstr = "/Pictures/";
                        switch (Cause) {
                            case 0:
                                Causestr = "进入重车拍照";
                                break;
                            case 1:
                                Causestr = "服务评价拍照";
                                break;
                            case 2:
                                Causestr = "报警拍照";
                                break;
                            case 3:
                                Causestr = "中心主动拍照";
                                break;
                            case 4:
                                Causestr = "ACCON拍照";
                                break;
                            case 5:
                                Causestr = "刷脸签到";
                                break;
                            case 6:
                                Causestr = "刷脸签退";
                                break;
                            case 7:
                                Causestr = "进入空车拍照";
                                break;
                            case 10:
                                Causestr = "定时拍照";
                                break;
                            case 12:
                                Causestr = "超速拍照";
                                break;
                            case 13:
                                Causestr = "出城拍照";
                                break;
                            case 14:
                                Causestr = "违规营运拍照";
                                break;
                            case 15:
                                Causestr = "刷脸签到拍照";
                                break;
                            case 19:
                                Causestr = "动态查岗拍照";
                                break;
                            case 20:
                                Causestr = "疲劳驾驶拍照";
                                break;
                            case 23:
                                Causestr = "分心驾驶拍照";
                                break;
                            case 22:
                                Causestr = "开车抽烟拍照";
                                break;
                            case 21:
                                Causestr = "开车打电话拍照";
                                break;
                            case 24:
                                Causestr = "异常驾驶报警";
                                break;
                            case 31:
                                Causestr = "乘客人脸拍照";
                                break;
                        }
                        mediatstr += (Causestr + "/") + fileParent + devTypestr;
                    }
                    break;
                    case 2: {
                        mediatstr = "/Audio/" + fileParent + devTypestr;
//                        if ((((MyApplication.BJBZ905 >> 0) & 0x01) == 1 || ((MyApplication.BJBZ905 >> 1) & 0x01) == 1)) {
//                            Causestr = "报警录音";
//                            mediatstr = "/Audio/" + Causestr + "/" +  fileParent + devTypestr;
//                        }
                    }
                    break;
                }

                File filePath = new File(path + "/CarMainMedia_" + putTextCPHM + mediatstr + (lock_flag.isEmpty() ? "" : lock_flag + "/"));

                if (!filePath.exists()) {
                    filePath.mkdirs();
                    // 创建新文件夹文件后缀号重置
                    if (isAddNumber)
                        getFileNumber(true, devType);
                }

                String fileName = "";
                if (isAddNumber) {
                    int fileNumber = getFileNumber(false, devType);
                    fileName = fileTime + tag + "-" + fileNumber;
                } else
                    fileName = fileTime + tag;

                pathname = filePath.getAbsolutePath() + "/" + fileName;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pathname;
    }

    public static int getFileNumber(boolean flag, int index) {
        if (index == -1)
            return 0;

        if (flag) {
            // 重置
            fileNumber[index] = 0;
        } else {
            // 自增
            fileNumber[index]++;
        }

        if (MyApplication.editor != null) {
            MyApplication.editor.putInt("FileNumber" + index, fileNumber[index]);
            MyApplication.editor.commit();
        }
        return fileNumber[index];
    }

    /**
     * SD卡剩余空
     *
     * @return
     */
    @SuppressWarnings("deprecation")
    public static int getUsSizeMB(String path) {
        StatFs fs = new StatFs(path);
        int sizemb = (int) (fs.getAvailableBlocks() * (fs.getBlockSize() / (1024f * 1024f)));
        LogUtils.d("Utils", path + "剩余空间" + sizemb + "MB");
        return sizemb;
    }

    /**
     * 返回文件夹内文件个数
     *
     * @param path
     * @return
     */
    public static int getUsNumber(String path, int nber) {
        int number = nber;
        File file = new File(path);
        if (file.exists()) {
            if (file.isFile()) {
                number++;
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (File f : files) {
                    number = getUsNumber(f.getAbsolutePath(), number);
                }
            }
        }
        return number;
    }


    /**
     * 去掉字符串中的中文
     *
     * @param itemlife
     * @return
     */
    public static String getCountChar(String itemlife) {

        String regEx = "[\\u4e00-\\u9fa5]";

        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(itemlife);

        return m.replaceAll("");
    }

    /**
     * 得到SD卡总大小GB
     *
     * @return
     */
    public static int getCountSizeGB(String path) {
        StatFs fs = new StatFs(path);
        if (fs != null) {
            return (int) (fs.getBlockCount() * (fs.getBlockSize() / (1024f * 1024f * 1024)));
        }
        return 0;
    }

    /**
     * 得到SD卡总大小MB
     *
     * @return
     */
    public static int getCountSizeMB(String path) {
        StatFs fs = new StatFs(path);
        if (fs != null) {
            return (int) (fs.getBlockCount() * (fs.getBlockSize() / (1024f * 1024f)));
        }
        return 0;
    }

    public static List<File> getFileLists(List<File> filelist, String path, String path1) {
        File file = new File(path1);
        if (file.exists()) {
            if (file.isFile()) {
                filelist.add(file);
            } else if (file.isDirectory()) {
                File filess[] = file.listFiles();

                String fileDate = new SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis());

                if (filess == null || filess.length == 0) {
                    // 不删除当天的文件夹
                    if (!path.equals(path1) && !path1.contains(fileDate)) {
                        if (file.delete()) {
                            LogUtils.d("Utils", "文件夹删除成功" + file.getAbsolutePath());
                        }
                    }
                    return filelist;
                }

                for (File f : filess) { // 遍历目录下所有的文件
                    if (f.isFile()) {
                        filelist.add(f);
                    } else if (f.isDirectory()) {
                        filelist = getFileLists(filelist, path, f.getAbsolutePath());
                    }
                }
            }
        }
        return filelist;
    }

    /**
     * 检查文件是否能复制或者删除
     *
     * @param filename
     * @return
     */
    public static boolean checkfile(String filename) {
        for (int i = 0; i < CamService.CamNumber; i++) {
            if (filename.equals(CamService.camParameters[i].savefilename) && CamService.camParameters[i].savefile) {
                return false;
            }
        }

        for (int i = 0; i < ServiceBinder.audioLoops.length; i++) {
            if (ServiceBinder.audioLoops[i] != null && (filename.equals(ServiceBinder.audioLoops[i].audio.inFileName) || filename.equals(ServiceBinder.audioLoops[i].audio.outFileName))) {
                return false;
            }
        }

//        //判断文件是否标记
//        if (filename.indexOf("_flag") > 0)
//            return false;
//
//        //判断文件是否报警
//        if (filename.indexOf("_alarm") > 0)
//            return false;

        return true;
    }

    /**
     * 根据SD卡剩余空间删除文件
     * 0:内置  1:外置
     */
    public static boolean deleteFileSize(String path, int sdType) {
        if (path.equals(getPath2())) {
            File dir = new File(getPath2_base());
            File[] fm = dir.listFiles();
            for (File file : fm) {
                if (file.getName().equals("LOST.DIR")) {
                    file.delete();
                    LogUtils.e("删除LOST.DIR文件夹成功  " + file.getAbsolutePath());
                }

                if (file.isDirectory() && (file.getName().indexOf("CarMainMedia") > -1 || file.getName().equals("LOST.DIR"))
                        && deleteFileSize(file.getAbsolutePath(), sdType)) {
                    return true;
                }
            }
        }

        boolean flag = false;
        File file = new File(path);
        // 默认外置小于1000MB 大于1500
        int lessMB = 1000;
        int moreMB = 1500;
        if (sdType == 0) {
            // 内置大小范围
            lessMB = 8000;
            moreMB = 8500;
        }
        if (file.exists()) {
            int UsMB = getUsSizeMB(path);
            if (UsMB < lessMB) {
                List<File> filelist = new ArrayList<File>();
                filelist = getFileLists(filelist, path, path);
                Collections.sort(filelist, new Comparator<File>() {
                    @Override
                    public int compare(File o1, File o2) {
                        return new Long(o1.lastModified()).compareTo(new Long(o2.lastModified()));
                    }
                });
                for (File f : filelist) {
                    //不删除正在保存的文件
                    if (!Utils.checkfile(f.getAbsolutePath()))
                        continue;

                    if (f.delete()) {
                        try {
                            // 是否要根据mediaID删除数据库数据
                            String fileName = f.getName();
                            int start = fileName.indexOf("-", 0) + 1;
                            String mediaID = fileName.substring(start, start + 10);
                            Bundle bundle = new Bundle();
                            bundle.putString("MediaID", mediaID);
                            if (MyApplication.mDvrManager != null && MyApplication.mDvrManager.mDvrCallBack != null && MyApplication.mDvrManager.bServiceConn)
                                MyApplication.mDvrManager.mDvrCallBack.doDeleteMedia(bundle);

                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        LogUtils.e("删除文件成功  " + f.getAbsolutePath());
                    }

                    UsMB = getUsSizeMB(path);
                    if (UsMB > moreMB) {
                        flag = true;
                        break;
                    }
                }
            } else {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 循环删除报警目录文件
     *
     * @param path      目录路径
     * @param limitSize 文件夹限制大小
     * @return
     */
    public static boolean deleteFileAlarm(String path, int limitSize) {
        if (path.equals(getPathAlarm())) {
            File dir = new File(getPath2_base());
            File[] fm = dir.listFiles();
            for (File file : fm) {
                if (file.getName().equals("LOST.DIR")) {
                    file.delete();
                    LogUtils.e("删除LOST.DIR文件夹成功  " + file.getAbsolutePath());
                }

                if (file.isDirectory() && (file.getName().indexOf("CarMainMedia") > -1 || file.getName().equals("LOST.DIR"))
                        && deleteFileAlarm(file.getAbsolutePath(), limitSize)) {
                    return true;
                }
            }
        }

        boolean flag = false;
        File file = new File(path);
        if (file.exists()) {
            double alarmMB = FileSizeUtil.getFileOrFilesSize(getPathAlarm(), FileSizeUtil.SIZETYPE_MB);
            LogUtils.d("报警文件夹大小  = " + alarmMB + "    限制大小 = " + limitSize);
            if (alarmMB >= limitSize) {
                List<File> filelist = new ArrayList<File>();
                filelist = getFileLists(filelist, path, path);
                Collections.sort(filelist, new Comparator<File>() {
                    @Override
                    public int compare(File o1, File o2) {
                        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HHmmss");
                        String name1 = o1.getName();
                        String name2 = o2.getName();
                        String time = "";
                        String time2 = "";
                        if (name1.lastIndexOf("-") > 0) {
                            time = name1.substring(0, name1.lastIndexOf("-"));
                        }
                        if (name2.lastIndexOf("-") > 0) {
                            time2 = (name2.substring(0, name2.lastIndexOf("-")));
                        }

                        try {
                            Date date1 = sdf.parse(time);
                            Date date2 = sdf.parse(time2);
                            // 按时间升序排序
                            return new Long(date1.getTime()).compareTo(new Long(date2.getTime()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        return new Long(o1.lastModified()).compareTo(new Long(o2.lastModified()));
                    }
                });
                for (File f : filelist) {
                    //不删除正在保存的文件
                    if (!Utils.checkfile(f.getAbsolutePath()))
                        continue;

                    if (f.delete()) {
                        String fileName = f.getName();
//                        int start = fileName.indexOf("-", 0) + 1;
//                        String mediaID = fileName.substring(start, start + 10);
                        // 是否要根据mediaID删除数据库数据
                        LogUtils.e("删除报警文件成功  " + f.getAbsolutePath());
                    }

                    alarmMB = FileSizeUtil.getFileOrFilesSize(getPathAlarm(), FileSizeUtil.SIZETYPE_MB);
                    LogUtils.d("删除后报警文件夹大小  = " + alarmMB + "    限制大小 = " + limitSize);
                    if (alarmMB < limitSize) {
                        flag = true;
                        break;
                    }
                }
            } else {
                flag = true;
            }
        }
        return flag;
    }

//    /**
//     * 根据文件个数删除文件
//     * @param path
//     */
//    public static boolean deleteFileNumber(String path) {
//        boolean flag = true;
//        File file = new File(path);
//        if (file.exists()) {
//            List<File> filelist = new ArrayList<File>();
//            filelist = getFileLists(filelist, path, path);
//            int number = filelist.size();
//            LogUtils.d("Utils", "flash文件个数  " + number);
//            if (MyApplication.sdnum != -1 && number > MyApplication.sdnum) {
//                Collections.sort(filelist, new Comparator<File>() {
//                    @Override
//                    public int compare(File o1, File o2) {
//                        return new Long(o1.lastModified()).compareTo(new Long(o2.lastModified()));
//                    }
//                });
//
//                for (File f : filelist) {
//                    //不删除正在保存的文件
//                    if (!Utils.checkfile(f.getAbsolutePath()))
//                        continue;
//
//                    if (f.delete()){
//                        //String fileName = f.getName();
//                        //int start = fileName.lastIndexOf("-") + 1;
//                        //String mediaID = fileName.substring(start, start + 10);
//                        // 是否要根据mediaID删除数据库数据
//
//                        LogUtils.d("Utils", "删除成功  " + f.getAbsolutePath());
//                        number--;
//                    }
//                    if (number <= MyApplication.sdnum) {
//                        break;
//                    }
//                }
//            }
//        }
//        return flag;
//    }

    // 合并图片
    public static Bitmap mergeBitmap(Bitmap mBitmap, String putText) {
        Canvas canva = new Canvas(mBitmap);
        canva.drawBitmap(mBitmap, 0, 0, null);

        Paint p = new Paint();
        Typeface font = Typeface.create("宋体", Typeface.BOLD);
        p.setColor(Color.RED);
        p.setTypeface(font);
        p.setTextSize(30);
        canva.drawText(putText, 50, 50, p);
       // canva.save(Canvas.ALL_SAVE_FLAG);
        canva.restore();

        return mBitmap;
    }

    /**
     * @param bm
     * @return
     */
    static ByteArrayOutputStream baos = new ByteArrayOutputStream();

    public static byte[] Bitmap2Bytes(Bitmap bm) {
        baos.reset();
        bm.compress(CompressFormat.JPEG, 60, baos);
        return baos.toByteArray();
    }

    public static Bitmap Bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }

    /***
     * 压缩GZip
     *
     * @param data
     * @return
     */
    public static byte[] gZip(byte[] data) {
        byte[] b = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(bos);
            gzip.write(data);
            gzip.finish();
            gzip.close();
            b = bos.toByteArray();
            bos.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return b;
    }

    public static String installAPK(String apkPath) {
        String[] args = {"pm", "install", "-r", apkPath};
        String result = "";
        ProcessBuilder processBuilder = new ProcessBuilder(args);
        Process process = null;
        InputStream errIs = null;
        InputStream inIs = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int read = -1;
            process = processBuilder.start();
            errIs = process.getErrorStream();
            while ((read = errIs.read()) != -1) {
                baos.write(read);
            }
            baos.write('\n');
            inIs = process.getInputStream();
            while ((read = inIs.read()) != -1) {
                baos.write(read);
            }
            byte[] data = baos.toByteArray();
            result = new String(data);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (errIs != null) {
                    errIs.close();
                }
                if (inIs != null) {
                    inIs.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (process != null) {
                process.destroy();
            }
        }
        return result;
    }

    /**
     * 执行shell命令 比如"reboot"
     *
     * @param command
     * @throws IOException
     */
    public static void execCommand(String command) throws IOException {

        LogUtils.e(" 执行shell命令 execCommand command = " + command);
        // 重启前停止录像
        if (command.equals("reboot"))
            CamService.closeVideo();
        Runtime runtime = Runtime.getRuntime();
        Process proc = runtime.exec(command);
        try {
            if (proc.waitFor() != 0) {
                System.err.println("exit value = " + proc.exitValue());
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    proc.getInputStream()));
            StringBuffer stringBuffer = new StringBuffer();
            String line = null;
            while ((line = in.readLine()) != null) {
                stringBuffer.append(line + "-");
            }
            System.out.println(stringBuffer.toString());

        } catch (InterruptedException e) {
            System.err.println(e);
        }
    }

    public static void writeUSBPowerFile(int bz) {
       /* FileWriter fw = null;
        try {
            fw = new FileWriter("/sys/devices/hall_common@0/con_usb_power");
            fw.write(bz + "");
            fw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }*/
    }

    /**
     * Bitmap转化为ARGB数据，再转化为NV21数据
     *
     * @param src    传入的Bitmap，格式为Bitmap.Config.ARGB_8888
     * @param width  NV21图像的宽度
     * @param height NV21图像的高度
     * @return nv21数据
     */
    public static byte[] bitmapToNv21(Bitmap src, int width, int height) {
        if (src != null && src.getWidth() >= width && src.getHeight() >= height) {
            int[] argb = new int[width * height];
            src.getPixels(argb, 0, width, 0, 0, width, height);
            return argbToNv21(argb, width, height);
        } else {
            return null;
        }
    }

    /**
     * ARGB数据转化为NV21数据
     *
     * @param argb   argb数据
     * @param width  宽度
     * @param height 高度
     * @return nv21数据
     */
    private static byte[] argbToNv21(int[] argb, int width, int height) {
        int frameSize = width * height;
        int yIndex = 0;
        int uvIndex = frameSize;
        int index = 0;
        byte[] nv21 = new byte[width * height * 3 / 2];
        for (int j = 0; j < height; ++j) {
            for (int i = 0; i < width; ++i) {
                int R = (argb[index] & 0xFF0000) >> 16;
                int G = (argb[index] & 0x00FF00) >> 8;
                int B = argb[index] & 0x0000FF;
                int Y = (66 * R + 129 * G + 25 * B + 128 >> 8) + 16;
                int U = (-38 * R - 74 * G + 112 * B + 128 >> 8) + 128;
                int V = (112 * R - 94 * G - 18 * B + 128 >> 8) + 128;
                nv21[yIndex++] = (byte) (Y < 0 ? 0 : (Y > 255 ? 255 : Y));
                if (j % 2 == 0 && index % 2 == 0 && uvIndex < nv21.length - 2) {
                    nv21[uvIndex++] = (byte) (V < 0 ? 0 : (V > 255 ? 255 : V));
                    nv21[uvIndex++] = (byte) (U < 0 ? 0 : (U > 255 ? 255 : U));
                }

                ++index;
            }
        }
        return nv21;
    }

    /**
     * I420转nv21
     *
     * @param data
     * @param width
     * @param height
     * @return
     */
    public static byte[] I420Tonv21(byte[] data, int width, int height) {
        byte[] ret = new byte[data.length];
        int total = width * height;

        ByteBuffer bufferY = ByteBuffer.wrap(ret, 0, total);
        ByteBuffer bufferV = ByteBuffer.wrap(ret, total, total / 4);
        ByteBuffer bufferU = ByteBuffer.wrap(ret, total + total / 4, total / 4);

        bufferY.put(data, 0, total);
        for (int i = 0; i < total / 4; i += 1) {
            bufferV.put(data[total + i]);
            bufferU.put(data[i + total + total / 4]);
        }

        return ret;
    }

}
